package com.cumt.websocket;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;

/**
 * 功能：websocket消息处理类，不要加入业务代码
 * Created by caicf on 2017/1/11.
 */
@ServerEndpoint("/ws/{path}")
public class WebSocketEndpoint {

    private static final Logger log = LoggerFactory.getLogger(WebSocketEndpoint.class);

    /**
     * 连接到Websocket时触发此方法
     *
     * @param path
     * @param session
     */
    @OnOpen
    public void onOpen(@PathParam("path") String path, Session session) {
        System.out.println("WebSocket opened: " + path + " " + session.getId());
        log.info("WebSocket opened: ");
        WsSessionUtil.put(path, session);
    }

    /**
     * 收到客户端消息时触发
     *
     * @param message
     * @param session
     */
    @OnMessage
    public String onMessage(@PathParam("path") String path, String message, Session session) {
        System.out.println("Message received: " + message);
        //TODO 打桩处理
        try {
            session.getBasicRemote().sendText(message.toUpperCase());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "received success";
    }

    /**
     * 客户端连接断开时触发
     * @param path
     * @param reason
     * @param session
     */
    @OnClose
    public void onClose(@PathParam("path") String path, CloseReason reason, Session session) {
        System.out.println("Closing a WebSocket due to " + reason.getReasonPhrase());
        WsSessionUtil.remove(path);
    }

    /**
     * 异常时触发
     * @param path
     * @param throwable
     * @param session
     */
    @OnError
    public void onError(@PathParam("path") String path, Throwable throwable, Session session) {
        log.info("Websocket Connection Exception -> path:{} cause:{}", path, throwable.getMessage());
        WsSessionUtil.remove(path);
    }
}
